package org.finesys.common.es.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.finesys.common.es.properties.MyElasticsearchProperties;
import org.finesys.common.es.util.ESUtil;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@EnableConfigurationProperties(MyElasticsearchProperties.class)
@RequiredArgsConstructor
@Slf4j
public class ElasticsearchClientConfig {
    //配置类
    private final MyElasticsearchProperties elasticsearchProperties;

    //加密工具类
    private final StringEncryptor stringEncryptor;

    /**
     * 创建一个JsonpMapper的Bean，用于处理JSON数据。
     *
     * @return 返回配置好的JsonpMapper实例，这里使用的是JacksonJsonpMapper。
     */
    @Bean
    public JsonpMapper jsonpMapper() {
        return new JacksonJsonpMapper();
    }

    /**
     * 创建一个Elasticsearch的同步客户端Bean。
     *
     * <p>此Bean通过同步方式提供Elasticsearch客户端的功能，适用于需要阻塞IO操作的场景。
     *
     * @return 配置好的ElasticsearchClient实例
     */
    @Bean
    public ElasticsearchClient elasticsearchClient(JsonpMapper jsonpMapper) {
        RestClientTransport restClientTransport = ESUtil.restClientTransport(elasticsearchProperties, jsonpMapper, stringEncryptor);
        return new ElasticsearchClient(restClientTransport);
    }

    /**
     * 创建一个Elasticsearch的异步客户端Bean。
     *
     * <p>此Bean通过异步方式提供Elasticsearch客户端的功能，适用于需要非阻塞IO操作的场景。
     *
     * @return 配置好的ElasticsearchAsyncClient实例
     */
    @Bean
    public ElasticsearchAsyncClient elasticsearchAsyncClient(JsonpMapper jsonpMapper) {
        RestClientTransport restClientTransport = ESUtil.restClientTransport(elasticsearchProperties, jsonpMapper, stringEncryptor);
        return new ElasticsearchAsyncClient(restClientTransport);
    }

}
